<!-- 如果不需要监听变更数据，就在父组件直接使用v-model:field="" -->
<template>
    <div class="">
        <van-field
            v-if="!readonly"
            :required="required"
            is-link
            :readonly="true"
            label="签名"
            placeholder="点击输入签名(支持单个输入)"
            @click="!readonly ? showPicker1 = true : ''"
        />
        <van-popup 
            v-model:show="showPicker1" 
            position="bottom"
        >
            <vue-esign 
                ref="esign"
                :isCrop="isCrop" 
                :lineWidth="lineWidth" 
                :lineColor="lineColor" 
                v-model:bgColor="bgColor" 
                :isClearBgColor="isClearBgColor"
                class="vue-esign"
            />
            <!-- isClearBgColor为false时，不必再给bgColor加sync修饰符或v-model -->
            <van-button 
                style="width: 50%" 
                @click="handleReset"
            >
                清空画板
            </van-button>
            <van-button 
                style="width: 50%" 
                @click="handleGenerate"
            >
                生成图片
            </van-button>
        </van-popup>

        <van-field
            :readonly="true"
            name="signList"
            label="签名图片"
            :rules="[{ required: required, message: '请在上一行点击签名' }]"
        >
            <template #input>
                <van-uploader 
                    :readonly="readonly"
                    v-model="signList" 
                    :show-upload="false" 
                    :before-delete="beforeDelete" 
                    :deletable="!readonly"
                    @delete="afterDelete" 

                />
            </template>
        </van-field>
        <canvas v-show="false" ref="canvas" style="width: 100vw; height: 50vw"></canvas>
    </div>
</template>

<script lang="ts" setup>
    import { ref, reactive, markRaw, watch } from 'vue';
    import type { Ref, Raw } from 'vue'
    import { showDialog, showLoadingToast, closeToast, showFailToast  } from 'vant'
    import { fileUploadBase64ExApi } from '@/apis'

    const props = withDefaults(defineProps<{
        readonly?: boolean,
        required?: boolean,
        modelValue?: string,
        // columns?: any[],
    }>(), {
        readonly: false,
        required: false,
        modelValue: '',
        // columns: () =>[],
    })
    
    // const { dataURL, readonly=false, modelValue } = defineProps<{
    //     dataURL?: any,
    //     readonly?: boolean,
    //     modelValue?: string,
    // }>()
    
    const emits = defineEmits<{
        (e: 'update:model-value', data: any): void,
    }>()
    
    const showPicker1: Ref<boolean> = ref(false)
    const signList = ref([])
    // 签字
    const lineWidth:Ref<number> = ref(6) //画笔粗细
    const lineColor:Ref<string> = ref('#000000') //画笔颜色
    const bgColor:Ref<string> = ref('rgb(255,255,255)') //画布背景色，为空时画布背景透明，支持多种格式 '#ccc'，'#E5A1A1'，'rgb(229, 161, 161)'，'rgba(255,255,255,1)'，'red'
    const isCrop:Ref<boolean> = ref(false) //是否裁剪，在画布设定尺寸基础上裁掉四周空白部分
    const isClearBgColor:Ref<boolean> = ref(false) //清空画布时(reset)是否同时清空设置的背景色
    const esign = ref(null)
    console.log(props.readonly)
    
    if (props.readonly) {
        watch(() => props.modelValue, (nVal, oVal) => {
            signList.value.push({
                url: props.modelValue,
                isImage: true
            })
        })
    } else if (props.modelValue) {
        signList.value.push({
            url: props.modelValue,
            isImage: true
        })
    }
    // 清空画板
    const handleReset  = () => {
        // console.log(esign)
        esign.value.reset()
    }
    // 生成图片
    const handleGenerate = () => {
        esign.value.generate().then(res => {
            showPicker1.value = false
            signList.value.push({
                url: res,
                isImage: true
            })
            handleReset()
            // 生成一张签名图片
            generateImg()
        }).catch(err => {
            // alert(err) // 画布没有签字时会执行这里 'Not Signned'
        })
    }
    // 删除图片之前
    const beforeDelete = (val) => {
        // console.log(val)
        return true
    }
    // 删除图片后
    const afterDelete = (file, detail) => {
        console.log(signList.value)
        // 生成一张签名图片
        generateImg()
    }
    // 生成图片列表
    const generateImg = () => {
        let imgCount = 0
        let images = []
        if (signList.value.length == 0) {
            drawImage(images)
        }
        signList.value.forEach((item) =>{
            const img = new Image()
            img.src = item.url
            images.push(img)
            img.onload = () =>{
                imgCount++
                // console.log(img)
                if (imgCount === signList.value.length) {
                    drawImage(images)
                }
            }
            
        })
    }
    const canvas = ref(null)
    // const dataURL = ref('')
    // canvas生成一张签名图片
    const drawImage = (images) => {
        emits('update:model-value', '')
        const ctx = canvas.value.getContext('2d')
        ctx.clearRect(0, 0, canvas.value.width, canvas.value.height);
        canvas.value.style.width = images.length * 100 + 'vw'
        images.forEach(async (img, index) =>{
            // ctx.drawImage(img, 0, 0, canvas.value.width / images.length, canvas.value.height, index * canvas.value.width / images.length, 0, canvas.value.width / images.length, canvas.value.height)
            // ctx.drawImage(img,0,0,100,100)
            ctx.drawImage(img, index * canvas.value.width / images.length, 0, canvas.value.width / images.length, canvas.value.height)
            // emits('update:model-value', canvas.value.toDataURL('image/png'))
            // dataURL.value=canvas.value.toDataURL('image/png'); //转换图片为dataURL
            if (index == images.length - 1) {
                try {
                    showLoadingToast({
                        message: '加载中...',
                        forbidClick: true,
                        duration: 0
                    })
                    let res1 = await fileUploadBase64ExApi({
                        data: canvas.value.toDataURL('image/png'),
                        sCode: 'kmxbyg'
                    })
                    emits('update:model-value', res1[0].url)


                } catch (err) {
                    // closeToast();
                    showFailToast('签名上传失败')
                    return;
                } finally {
                    closeToast();
                }
            }
        })
    }
</script>

<style lang="scss" scoped>
    :deep(.van-uploader__preview-image) {
        width: 50px;
        height: 50px;
    }
</style>